package com.xsherl.leetcode.solution;

import com.xsherl.leetcode.base.TreeNode;
import com.xsherl.leetcode.utils.TreeUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class UniqueBinarySearchTrees2 {

    public List<TreeNode> generateTrees(int n) {
        if (n == 0) {
            return new ArrayList<>();
        }
        return generate(1, n);
    }

    public List<TreeNode> generate(int begin, int end){
        List<TreeNode> list = new ArrayList<>();
        if (begin > end){
            list.add(null);
            return list;
        }
        // 枚举可行根节点
        for (int i = begin; i <= end; ++i){
            // 获得所有可行的左子树集合
            List<TreeNode> leftTrees = generate(begin, i - 1);
            // 获得所有可行的右子树集合
            List<TreeNode> rightTrees = generate(i + 1, end);
            for (TreeNode left : leftTrees) {
                for (TreeNode right : rightTrees) {
                    TreeNode node = new TreeNode(i, left, right);
                    list.add(node);
                }
            }
        }
        return list;
    }


    public static void main(String[] args) {
        int n = 3;
        List<TreeNode> treeNodes = new UniqueBinarySearchTrees2().generateTrees(n);
        System.out.println(treeNodes.size());
        List<List<Integer>> collect = treeNodes.stream().map(TreeUtils::preorderTraversal).collect(Collectors.toList());
        System.out.println(collect);
    }
}
